/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 7/9/13
 * Time: 16:48
 * To change this template use File | Settings | File Templates.
 */
var request = require('request');
var when = require('when');
var image = require('../lib/image.js');
var spawn = require('child_process').spawn;
var dao = require('../dao/index.js');

function getVideoInfo(id) {
    var deferred = when.defer();
    var url = 'https://openapi.youku.com/v2/videos/show.json?client_id=6b13b6f6fb4099b6&video_id=' + id;
    request({
        url : url
    }, function(err, resp, body) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(body || resp.body);
        }
    });
    //deferred.resolve(doc);
    return deferred.promise;
}

function getMusicList(keyword, page) {
    var deferred = when.defer();
    var referer = '"http://www.diandian.com/dianlog/rekey/new/audio"';
    var url = 'http://kuang.xiami.com/app/nineteen/search/key/' + encodeURIComponent(keyword) + '/diandian/1/page/' + page;
    var curl = spawn('curl', [url, '-e', referer]);
    var _str = '';
    curl.stdout.on('data', function(data) {
        _str += data.toString();
    });
    curl.on('exit', function(code) {
        if (code == 0) {
            _str = _str.replace(/\+/g, ' ');
            _str = decodeURIComponent(_str);
            deferred.resolve(JSON.parse(_str));
        } else {
            deferred.reject({
                'errcode' : code
            });
        }
    });
    return deferred.promise;
}

function uploadCoverCDN(cover, callback) {
    request({
        url : 'http://cdn.youqu.us/upload?url=' + cover
    }, function(err, res, body) {
        try {
            callback(JSON.parse(body));
        } catch (e) {
            console.error(e);
            callback({});
        }
    });
}

exports.get = function(req, res) {
    var type = req.param('type'), u = req.param('u') ? req.param('u').trim() : '', page = req.param('page') || 1;
    if (type == 'video') {
        var id = u.replace('http://v.youku.com/v_show/id_', '').replace('.html', '');
        getVideoInfo(id).then(function(body) {
            body = JSON.parse(body);
            res.jsonp({
                id : body.id,
                video_id : body.id,
                cover : body.bigThumbnail,
                tags : body.tags,
                title : body.title,
                source : u,
                description : body.description
            });
        });
    }
    if (type == 'image') {

    }
    if (type == 'music') {
        getMusicList(u, page).then(function(body) {
            res.set('Cache-Control', 'public, max-age=25920000');
            res.jsonp(body);
        });
    }
};

exports.create = function(req, res) {
    if (!res.locals.user || !res.locals.user._id) {
        res.redirect('/signin');
    } else {
        var type = req.param('type');
        var data = {
            type : type
        };
        data[type] = req.body;
        dao.media.create(data).then(function(doc) {
            res.json(doc);
            if (doc.type == 'music') {
                var cover = doc.music.album_logo.replace(/_[\d]{1}/, '_4');
                uploadCoverCDN(cover, function(json) {
                    if (json.url) {
                        doc._doc.music.album_logo = json.url;
                        dao.media.update(doc._id, {
                            $set : {
                                music : doc._doc.music
                            }
                        }, function(err) {
                            console.log(err);
                        });
                    }
                });
            }
        });
    }
};